package com.qf.servlet;


import com.qf.entity.Message;
import com.qf.service.MessageService;
import com.qf.service.impl.MessageServiceImpl;
import com.qf.utils.JsonUtils;
import com.qf.utils.ResultVo;

import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.time.LocalDateTime;

@WebServlet(urlPatterns = "/messageServlet")
public class MessageServlet extends BaseServlet{
    private MessageService messageService;
    private ResultVo resultVo;
    @Override
    public void init(ServletConfig config) throws ServletException {
        messageService = new MessageServiceImpl();
    }

    public void addMessage(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String uid = req.getParameter("uid");
        String detail = req.getParameter("detail");
        //获取message
        if(uid==null || "".equals(uid)){
            resultVo = ResultVo.error(500,"非法登录");
        }else if(detail==null || "".equals(detail)){
            resultVo = ResultVo.error(500,"留言不能为空");
        }else {
            Message message = new Message();
            message.setPublic_date(LocalDateTime.now());
            message.setDetail(detail);
            int num = messageService.addMessage(message, Integer.parseInt(uid));
            if(num==-1){
                resultVo  = ResultVo.error(500,"您没有借书卡，不能留言");
            }else if(num>0){
                resultVo = ResultVo.success(200,"留言成功",num);
            }else {
                resultVo = ResultVo.error(500,"留言失败");
            }
        }
        JsonUtils.toJsonString(resultVo,resp);
    }
}
